package lambda.lambda_easy_demo;

import lambda.Apple;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Comparator;
import java.util.function.*;

/**
 * Description: Lambda简单示例
 *
 * @author code-worker
 * @date 2021/10/09 7:15
 */
public class Lambda {

    void lambdaCompare(){
        //不使用lambda
        Comparator<Apple> compareByWeight = new Comparator<Apple>() {
            @Override
            public int compare(Apple apple, Apple t1) {
                return apple.getWeight().compareTo(t1.getWeight());
            }
        };
        //使用lambda
        Comparator<Apple> compareByWeightLambda = (Apple a, Apple b) -> a.getWeight().compareTo(b.getWeight());
        //使用简化lambda
        Comparator<Apple> compareByWeightLambda2 = Comparator.comparing(Apple::getWeight);
    }

    void lambdaDemo(){
        //有入参出参
        Function<String, Integer> function = (String s) -> s.length();
                                  function = String::length;
        //具有两个入参，一个出参
        BiFunction<String, String, Integer> biFunction = (String s1, String s2) -> (s1 + s2).length();
        //具有入参，返回boolean
        Predicate<String> predicate = (String s) -> s.length() > 1;
        //具有两个入参，返回boolean
        BiPredicate<String, String> biPredicate = (String s1, String s2) -> (s1+s2).length() > 1;
        //无入参，有出参
        Supplier<Integer> supplier = () -> 42;
        //无入参，有对象出参
        Supplier<Apple> supplier2 = () -> new Apple(100, "red");
        //有入参，出参为void
        Consumer<String> consumer = (String s) -> System.out.println(s.length());
        //有两个入参，出参为void
        BiConsumer<String, String> biConsumer = (String s1, String s2) -> System.out.println((s1 + s2).length());
        //有入参和出参，且类型相同
        UnaryOperator<String> unaryOperator = (String s) -> s+s;
        //有两个入参和一个出参，且类型相同
        BinaryOperator<Boolean> binaryOperator = (Boolean isTrue, Boolean isFalse) -> isTrue && isFalse;
    }

    void testException(){
        Function<BufferedReader, String> f = b -> {
            try{
                return b.readLine();
            }catch(IOException e){
                throw new RuntimeException(e);
            }
        };
    }

}
